import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:video_demo/view/error_view.dart';
import 'package:video_demo/view/progress_view.dart';
import 'package:video_demo/view/sucess_view.dart';

class VideoView extends StatefulWidget {
  @override
  _VideoViewState createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
  Future<void> _future;
  final FijkPlayer player = FijkPlayer();

  Future<void> _getUrlAndReadyToPlay() async {
    var response = await Dio().post("http://192.168.110.157:8081/media/start",
        data: {"id": 3, "type": "http"});
    var result = json.decode(response.toString());
    var url = result['data'].toString();
    await player.setDataSource(url, autoPlay: true);
  }

  Future<void> _getUrlAndReadyToPlay2() async {
    var url = "http://1011.hlsplay.aodianyun.com/demo/game.flv";
    await player.setDataSource(url, autoPlay: true);
  }

  @override
  void initState() {
    super.initState();
    //_future = _getUrlAndReadyToPlay();
    _future = _getUrlAndReadyToPlay2();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
        future: _future,
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            print(snapshot.error);
            return ErrorView();
          }
          switch (snapshot.connectionState) {
            case ConnectionState.done:
              return SuccessView(player);
            case ConnectionState.none:
            case ConnectionState.waiting:
            case ConnectionState.active:
            default:
              return ProgressView();
          }
        },
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    player.dispose();
  }
}
